package com.inifitness.admin.core.config.mp.handler;

import java.time.LocalDateTime;
import java.util.Optional;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.inifitness.admin.core.security.model.SysUserDetails;
import com.inifitness.admin.core.security.util.SecurityUtils;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * mybatis-plus 字段自动填充
 *
 * @author sunjinfeng
 * @since 2024/04/18 11:00:00
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

  /**
   * 新增填充创建时间
   *
   * @param metaObject 元数据
   */
  @Override
  public void insertFill(MetaObject metaObject) {
    this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
    this.strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
    this.strictInsertFill(metaObject, "createBy", String.class,
        Optional.ofNullable(SecurityUtils.getUser()).map(SysUserDetails::getUsername).orElse(""));
    this.strictInsertFill(metaObject, "updateBy", String.class,
        Optional.ofNullable(SecurityUtils.getUser()).map(SysUserDetails::getUsername).orElse(""));
    this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
  }

  /**
   * 更新填充更新时间
   *
   * @param metaObject 元数据
   */
  @Override
  public void updateFill(MetaObject metaObject) {
    this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
    this.strictUpdateFill(metaObject, "updateBy", String.class,
        Optional.ofNullable(SecurityUtils.getUser()).map(SysUserDetails::getUsername).orElse(""));
  }

}
